package com.huirui.server.util;

import com.huirui.server.constant.TokenConstant;
import com.huirui.server.exception.AuthorityException;
import com.huirui.server.properties.JwtProperties;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.security.Keys;
import jakarta.annotation.PostConstruct;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.crypto.SecretKey;
import java.util.Base64;
import java.util.Date;

@Slf4j
@Component
public class JwtUtil {

    @Resource
    private JwtProperties jwtProperties;

    private SecretKey miniProgramSecretKey;
    private SecretKey adminSecretKey;


    @PostConstruct
    public void init() {
        log.info("init JwtUtil SecretKey");
        miniProgramSecretKey = Keys.hmacShaKeyFor(Base64.getDecoder().decode(jwtProperties.getMiniProgramSecret()));
        adminSecretKey = Keys.hmacShaKeyFor(Base64.getDecoder().decode(jwtProperties.getAdminTokenSecret()));
    }


    public String createToken(Long id) {
        return Jwts.builder()
                .claim(TokenConstant.USER_ID, id)
                .issuedAt(new Date())
                .expiration(new Date(System.currentTimeMillis() + jwtProperties.getMiniProgramExpiration()))
                .signWith(miniProgramSecretKey)
                .compact();
    }

    public Long parseToken(String token) {
        long id;
        try {
            Claims payload = Jwts.parser()
                    .verifyWith(miniProgramSecretKey)
                    .build()
                    .parseSignedClaims(token)
                    .getPayload();
            id = payload.get(TokenConstant.USER_ID, Long.class);
        } catch (Exception e) {
            throw new AuthorityException(e.getMessage());
        }
        return id;
    }

    public String createAdminToken(Long id) {
        return Jwts.builder()
                .claim(TokenConstant.ADMIN_ID, id)
                .issuedAt(new Date())
                .expiration(new Date(System.currentTimeMillis() + jwtProperties.getAdminExpiration()))
                .signWith(adminSecretKey)
                .compact();
    }

    public Long parseAdminToken(String token) {
        long id;
        try {
            Claims payload = Jwts.parser()
                    .verifyWith(adminSecretKey)
                    .build()
                    .parseSignedClaims(token)
                    .getPayload();
            id = payload.get(TokenConstant.ADMIN_ID, Long.class);
        } catch (Exception e) {
            throw new AuthorityException(e.getMessage());
        }
        return id;
    }
}
